import socket
import pickle

OK = "mkay"
ACCEPTED = "accepted"
REJECTED = "rejected"
HELLO = "hello"
NLIST = "nlist"
FLIST = "flist"
NFLIST = "nflist"
NEIGHBOR = "neighbor"
NNEIGHBORS = "nneighbors"
DROPPED = "dropped"
PING = "ping"
PONG = "pong"
FILE = "file"
FIND = "find"
FOUND = "found"
GET = "get"

REMOVED = "rm"
ADDED = "a"

def comm(ip, port, name, cmd, data=None):
  try:
    out = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    out.connect((ip, port))
    msg = (name, cmd, data)
    out.send(pickle.dumps(msg))
    out.shutdown(socket.SHUT_WR)
    data = ""
    while 1:
      inp = out.recv(1024)
      if not inp: break
      data += inp
    out.close()
    
    if data is "":
      raise PeerDisconnectedError(ip, port)
    
    return pickle.loads(data)
  except socket.error:
    raise PeerDisconnectedError(ip, port)

class PeerDisconnectedError(Exception):
  def __init__(self, ip, port):
    self.ip = ip
    self.port = port

  def __str__(self):
    return 'Peer disconnected: ' + str(self.ip) + ':' + str(self.port)
